<?php

class TFsBOXConfig
	{
		private $cache;
		private $path;

		function __construct($path)
			{
				$this->path = $path;
				$this->cache = parse_ini_file($path, true);

				if (!is_writable($path) && TFsBOX_DEBUG)
					TFsBOXSession::storeError("File ". basename($path) ." is not writable.");
			}

		function __destruct()
			{
				$this->save();
			}

		function save()
			{
				$ini = "";
				foreach (array_keys($this->cache) as $key)
				{
					// Has sub keys ...
					if (is_array($this->cache[$key]))
					{
						$ini .= "[$key]\n";
						foreach (array_keys($this->cache[$key]) as $sub_key)
						{
							$val = $this->cache[$key][$sub_key];
							$ini .= "$sub_key = ";

							if (is_string($val))
								$ini .= '"'.$val.'"';
							else
								$ini .= $val;

							$ini .= "\n";
						}
					}

					// Does not have sub keys ...
					else
					{
						$val = $this->cache[$key];
						$ini .= "$key = ";

						if (is_string($val))
							$ini .= '"'.$val.'"';
						else
							$ini .= $val;
					}

					$ini .= "\n";
				}

				file_put_contents($this->path, $ini);
			}

		function setValue($key, $value)
			{
				$split = explode("/", $key);
				if (count($split) > 1)
					$this->cache[$split[0]][$split[1]] = $value;
				else
					$this->cache[$key] = $value;
			}

		function value($key, $default_value = NULL)
			{
				$split = explode("/", $key);
				if (count($split) > 1)
					$val = $this->cache[$split[0]][$split[1]];
				else
					$val = $this->cache[$key];

				return (isset($val)) ? $val : $default_value;
			}
	}

?>
